/*
 *
 *  * Copyright (c) 2016. For Intelligent Group.
 *
 */
package com.intelligent.ispc.client.core.view.system;

import com.intelligent.ispc.client.core.controller.ScriptController;
import com.intelligent.ispc.client.core.view.AbstractPanel;
import com.intelligent.ispc.client.ex.JTextFieldEx;
import com.intelligent.ispc.client.utils.AppMessageFactory;
import com.intelligent.ispc.client.utils.FileUtils;
import com.intelligent.ispc.client.utils.GBC;
import com.intelligent.ispc.common.mapper.JsonMapper;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.StringUtils;

import com.intelligent.ispc.constant.AppConstant;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.PostConstruct;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import java.util.List;

/**
 * Created by Qiang.Chen on 2016/9/7.
 */
@org.springframework.stereotype.Component
public class ScriptTestPanel extends AbstractPanel {

    @Autowired
    private ScriptController scriptController;

    public ScriptTestPanel() {
    }

    @Override
    public void initDataSource() {

    }

    @Override
    public void initView() {

    }

    @PostConstruct
    @Override
    public void initComponents() {
        inputPanel = new JPanel();
        resultPanel = new JPanel(new GridBagLayout());
        filePathLbl = new JLabel("CSV File");
        scriptPathLbl = new JLabel("Python script");
        filePathTf = new JTextFieldEx();
        scriptPathTf = new JTextFieldEx();
        testScriptBtn = new JButton("Test");
        csvBrowseButton = new JButton("Browse");
        scriptBrowseButton = new JButton("Browse");
        table = new JTable();

        inputPanel.setLayout(new GridBagLayout());
        inputPanel.setBorder(BorderFactory.createTitledBorder("Test Python Script"));
        inputPanel.add(filePathLbl, new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(5, 0).setInsets(5, 5, 0, 0));
        inputPanel.add(filePathTf, new GBC(1, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(5, 5, 0, 0));
        inputPanel.add(csvBrowseButton, new GBC(2, 0).setFill(GBC.HORIZONTAL).setWeight(5, 0).setInsets(5, 5, 0, 0));

        inputPanel.add(scriptPathLbl, new GBC(0, 1).setFill(GBC.HORIZONTAL).setWeight(5, 0).setInsets(5, 5, 0, 0));
        inputPanel.add(scriptPathTf, new GBC(1, 1).setFill(GBC.HORIZONTAL).setWeight(100, 0).setInsets(5, 5, 0, 0));
        inputPanel.add(scriptBrowseButton, new GBC(2, 1).setFill(GBC.HORIZONTAL).setWeight(5, 0).setInsets(5, 5, 0, 0));

        inputPanel.add(testScriptBtn, new GBC(1, 2, 2, 1).setInsets(5, 5, 5, 5).setAnchor(GBC.WEST));

        hintLbl = new JLabel();
        searchKeysLbl = new JLabel();
        attributeKeysLbl = new JLabel();

        resultScrollPane = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        resultScrollPane.setPreferredSize(new java.awt.Dimension(250, 180));

        resultPanel.add(hintLbl, new GBC(0, 0).setFill(GBC.BOTH).setInsets(5, 0, 10, 0));
        resultPanel.add(searchKeysLbl, new GBC(0, 1).setFill(GBC.BOTH).setInsets(5, 0, 10, 0));
        resultPanel.add(attributeKeysLbl, new GBC(0, 2).setFill(GBC.BOTH).setInsets(5, 0, 10, 0));
        resultPanel.add(resultScrollPane, new GBC(0, 3).setFill(GBC.BOTH).setWeight(100, 100));
        resultPanel.setBorder(BorderFactory.createTitledBorder("Test Result"));

        this.setLayout(new GridBagLayout());
        this.add(inputPanel, new GBC(0, 0).setFill(GBC.HORIZONTAL).setWeight(100, 0));
        this.add(resultPanel, new GBC(0, 1).setFill(GBC.BOTH).setWeight(100, 100));
        this.setVisible(true);
        initComponentsEvent();
    }

    private void initComponentsEvent() {
        testScriptBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                List<String> result = null;
                hintLbl.setText("");
                searchKeysLbl.setText("");
                attributeKeysLbl.setText("");
                DefaultTableModel defaultModel = new DefaultTableModel();
                table.setModel(defaultModel);

                try {
                    if (!filePathTf.getText().isEmpty() && !scriptPathTf.getText().isEmpty()) {
                        int rowNum = 10;
                        int columnNum = 10;
                        String filePath = filePathTf.getText().replaceAll("\\\\", "/");
                        String scriptPath = scriptPathTf.getText().replaceAll("\\\\", "/");
                        String scriptName = scriptPath.substring(scriptPath.lastIndexOf("/") + 1);

                        if (scriptName.equals(AppConstant.PATH_SCRIPT_FILENAME)) {
                            AppMessageFactory.showWarningDialog("The selected python script has the " + "\n"
                                    + "same name as the system python script." + "\n" + "Please modify the python script name.");
                        } else {
                            result = scriptController.testScript(filePath, scriptPath, rowNum, columnNum);
                            JsonMapper jsonMapper = new JsonMapper();

                            if (result != null && result.size() > 1) {
                                hintLbl.setText("The display of the top 10 parsed results : ");
                                searchKeysLbl.setText(AppConstant.DATA_SEARCH_KEYS + " : " + result.get(1));
                                attributeKeysLbl.setText(AppConstant.DATA_SEARCH_KEYS + " : " + result.get(2));

                                String[] name = new String[rowNum + 4];
                                name[0] = "Title";
                                name[1] = "Upper Limit";
                                name[2] = "Lower Limit";
                                name[3] = "Measurement Unit";
                                for (int i = 0; i < result.size() - 3; i++) {
                                    name[i + 4] = String.valueOf(i + 1);
                                }
                                defaultModel.addColumn("", name);

                                for (int i = 0; i < result.size(); i++) {
                                    if (i < 3) {
                                        continue;
                                    }

                                    Map<String, Object> data = jsonMapper.fromJson((String) result.get(i), jsonMapper.contructMapType(Map.class, String.class, Object.class));
                                    Vector<String> value = new Vector<String>();

                                    value.add(data.get("n").toString());

                                    String[] params = data.get("params").toString().replace(",", " , ").split(",");
                                    value.add(params[0].trim());
                                    value.add(params[1].trim());
                                    value.add(params[2].trim());
                                    data.remove("n");
                                    data.remove("params");
                                    data.remove("i");

                                    for (int j = 0; j < data.size(); j++) {
                                        value.add(data.get("data" + j).toString());
                                    }
                                    defaultModel.addColumn("", value);
                                }

                                table.setPreferredScrollableViewportSize(new Dimension(250, 180));
                                table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);

                                resultScrollPane.setViewportView(table);
                                resizeTable(true, resultScrollPane, table);
                            }
                        }
                    }
                } catch (ApplicationException ex) {

                }
            }
        });

        csvBrowseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                csvBrowseButtonActionPerformed(evt);
            }
        });

        scriptBrowseButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent evt) {
                scriptBrowseButtonActionPerformed(evt);
            }
        });
    }

    private void csvBrowseButtonActionPerformed(ActionEvent evt) {
        String selectedFiles = FileUtils.filePathSelect(ScriptTestPanel.this);
        if (!StringUtils.isBlank(selectedFiles)) {
            filePathTf.setText(selectedFiles);
        }
    }

    private void scriptBrowseButtonActionPerformed(ActionEvent evt) {
        String selectedFiles = FileUtils.filePathSelect(ScriptTestPanel.this);
        if (!StringUtils.isBlank(selectedFiles)) {
            scriptPathTf.setText(selectedFiles);
        }
    }

    public void filePathError(String message) {
        AppMessageFactory.showErrorDialog(message);
    }

    public void scriptError(String message) {
        AppMessageFactory.showErrorDialog(message);
    }

    private JPanel inputPanel;
    private JPanel resultPanel;
    private JLabel hintLbl;
    private JLabel searchKeysLbl;
    private JLabel attributeKeysLbl;
    private JScrollPane resultScrollPane;
    private JTable table;
    private JLabel filePathLbl;
    private JLabel scriptPathLbl;
    private JTextField filePathTf;
    private JTextField scriptPathTf;
    private JButton testScriptBtn;
    private JButton csvBrowseButton;
    private JButton scriptBrowseButton;

    public void resizeTable(boolean bool, JScrollPane scrollPane, JTable table) {
        Dimension containerwidth = null;
        if (!bool) {
            containerwidth = scrollPane.getPreferredSize();
        } else {
            containerwidth = scrollPane.getSize();
        }

        int allwidth = table.getIntercellSpacing().width;
        for (int j = 0; j < table.getColumnCount(); j++) {
            int max = 0;
            for (int i = 0; i < table.getRowCount(); i++) {
                int width = table.getCellRenderer(i, j).getTableCellRendererComponent(table, table.getValueAt(i, j),
                        false, false, i, j).getPreferredSize().width;
                if (width > max) {
                    max = width;
                }
            }

            max += 20;
            table.getColumnModel().
                    getColumn(j).setPreferredWidth(max);
            allwidth += max + table.getIntercellSpacing().width;
        }
        allwidth += table.getIntercellSpacing().width;
        if (allwidth > containerwidth.width && containerwidth.width != 0) {
            table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        } else {
            table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        }
    }
}
